package com.yuliang.ai.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.yuliang.ai.domain.Dto.AiConfigDto;
import com.yuliang.ai.domain.Vo.*;
import com.yuliang.ai.logic.AiOperation;
import com.yuliang.ai.request.LoginUtils;
import com.yuliang.ai.service.AiConfigService;
import com.yuliang.ai.service.AiUiService;
import com.yuliang.ai.websocket.WebSocketServer;
import com.yuliang.utils.DistributedLock.Lock;
import com.yuliang.utils.DistributedLock.RedisLockClient;
import com.yuliang.utils.result.ResultUtils;
import com.yuliang.utils.result.emums.HttpCodeEnum;
import com.yuliang.utils.util.CreateSign;
import com.yuliang.utils.util.HttpRequestUtils;
import com.yuliang.utils.util.RedisUtils;
import com.yuliang.utils.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author Huangkai
 */
@Slf4j
@Service
public class AiUiServiceImpl implements AiUiService {

    @Value("${spring.login.username}")
    private String username;

    @Value("${spring.login.password}")
    private String password;

    @Autowired
    AiOperation aiOperation;

    @Autowired
    AiUiService aiUiService;

    @Autowired
    RedisLockClient redisLockClient;

    @Autowired
    WebSocketServer messagePushWebSocket;

    @Autowired
    AiConfigService aiConfigService;


    @Override
    public String aiuiOperation(HttpServletRequest request, String token) {
        try{
            String getContentType = request.getMethod();
            if("GET".equals(getContentType)){
                Map<String, String[]> parameterMap = request.getParameterMap();
                ArrayList<String> signList = new ArrayList<>();
                signList.add(token);
                signList.add(parameterMap.get("rand")[0]);
                signList.add(parameterMap.get("timestamp")[0]);
                Collections.sort(signList);
                StringBuffer stringBuffer = new StringBuffer();
                for(String str : signList) {
                    stringBuffer.append(str);
                }
                String shaEncode = DigestUtils.sha1Hex(stringBuffer.toString());
                log.info("加密的数据{}", shaEncode);
                return DigestUtils.sha1Hex(token);
            }else {
                log.info("aiui开始调用=================================================");
                BufferedReader reader = request.getReader();
                StringBuilder builder = new StringBuilder();
                String line = reader.readLine();
                while (line != null) {
                    builder.append(line);
                    line = reader.readLine();
                }
                reader.close();
                String reqBody = builder.toString();
                log.info("aiui传过来的信息{}", reqBody);
                AiuiBodyVo aiuiBodyVo = JSONObject.parseObject(reqBody, AiuiBodyVo.class);
                String userParams = aiuiBodyVo.getUserParams();
                //获取设备信息
                byte[] otherParamsByte = Base64.getDecoder().decode(userParams);
                //获取deviceId
                String otherParamsJson = new String(otherParamsByte, "utf-8");
                JSONObject jsonObject = JSONObject.parseObject(otherParamsJson);
                log.info("获取值{}", jsonObject);
                //获取body实体内容
                String contentBase64 = aiuiBodyVo.getMsg().getContent();
                byte[] base64decodedBytes = Base64.getDecoder().decode(contentBase64);
                String result = new String(base64decodedBytes, "utf-8");
                AiContentVo aiContentVo = JSONObject.parseObject(result, AiContentVo.class);
                log.info("aiui传过来的设备信息{}", aiContentVo);
                String text = aiContentVo.getIntent().getText();
                if(aiContentVo.getIntent().getRc() != null){
                    //如果等于4，则走百川大模型
                    if(aiContentVo.getIntent().getRc() == 4){
                        //获取配置的值
                        AiConfigVo aiConfigVo = new AiConfigVo();
                        aiConfigVo.setConfigKey("sys_ai_length");
                        AiConfigDto aiConfigDto = aiConfigService.selectAiConfig(aiConfigVo);
                        if(text.length() >= Integer.parseInt(aiConfigDto.getConfigValue())){
                            String sid = aiContentVo.getIntent().getSid();
                            Lock lock = redisLockClient.getLock(sid);
                            boolean isLock = lock.tryLock(0, 5, TimeUnit.MINUTES);
                            log.info("是否锁定{}", isLock);
                            if(isLock){
                                try{
                                    int type = 1;
                                /*
                                if(jsonObject.containsKey("bigModelType")){
                                    type = Integer.parseInt(jsonObject.getString("bigModelType"));
                                }
                                 */
                                    if(type == 0){
                                        aiOperation.qingBo(jsonObject, text);
                                    }else{
                                        aiOperation.douBaoBotChatCompletions(aiOperation.buildChatDoubaoVo(jsonObject, text));
                                    }
                                }catch (Exception exception){
                                    exception.printStackTrace();
                                }finally {
                                    lock.unlock();
                                }
                            }
                        }else{
                            List<String> videoPathList = new ArrayList<>();
                            List<String> imgList = new ArrayList<>();
                            JSONObject resultJSON = new JSONObject();
                            resultJSON.put("videoPathList", videoPathList);
                            resultJSON.put("imgList", imgList);
                            resultJSON.put("content", "大模型处理字数不够，请重新提交！");
                            resultJSON.put("isEnd", 1);
                            messagePushWebSocket.sendOneMessage(jsonObject.getString("deviceId"), resultJSON);
                        }
                    }
                }
                JSONObject customData = new JSONObject();
                customData.put("key", "custom");
                customData.put("content", text);
                return customData.toJSONString();
            }
        }catch (IOException ioException){
            return null;
        }
    }

    @Override
    public String getVideoStream(JSONObject jsonObject, String text) {
        return aiOperation.douBaoBotChatVideo(aiOperation.buildChatDoubaoVo(jsonObject, text));
    }

    @Override
    public String chatAnslist(ChatAnsVo chatAnsVo) {
        if(!RedisUtils.hasKey("token")){
            LoginUtils.loginOperation(username, password);
        }
        log.info("传过来的值{}", chatAnsVo);
        String token = RedisUtils.get("token");
        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json; charset=UTF-8");
        header.put("Authorization", token);
        JSONObject jsonObject = new JSONObject();
        if(chatAnsVo.getChatId() != null){
            jsonObject.put("chat_id", chatAnsVo.getChatId());
        }
        jsonObject.put("page", chatAnsVo.getPage());
        jsonObject.put("limit", chatAnsVo.getLimit());
        String responseContent = HttpRequestUtils.doPost("http://lsjllm.gsdata.cn:8066/api/chat/index/chat-ans", header, jsonObject.toJSONString());
        JSONObject resultObject = JSONObject.parseObject(responseContent);
        System.out.println(resultObject);
        if(resultObject.getInteger("code") == 10000){
            JSONObject dataObject = resultObject.getJSONObject("data");
            if(!dataObject.isEmpty()){
                return ResultUtils.ResultWithDataEnum(HttpCodeEnum.select_success, dataObject);
            }
            return ResultUtils.ResultWithMessageEnum(HttpCodeEnum.data_not_exist);
        }
        return ResultUtils.ResultWithMessageEnum(HttpCodeEnum.chartGpt_error);
    }

    @Override
    public String stopChatAns(ChatVo chatVo){
        log.info("调用打断。。。。。。");
        if(StringUtils.isEmpty(chatVo.getDeviceId()) || StringUtils.isEmpty(chatVo.getRequestId())){
            return ResultUtils.ResultWithMessageEnum(HttpCodeEnum.not_stop);
        }
        String connectionKey = chatVo.getDeviceId() + chatVo.getUserId() + chatVo.getHumanIdentifyId();
        if(RedisUtils.hasKey(connectionKey)){
            String requestId = RedisUtils.get(connectionKey);
            if(requestId.equals(chatVo.getRequestId())){
                return ResultUtils.ResultWithMessageEnum(HttpCodeEnum.in_stop);
            }
            //设置打断参数
            RedisUtils.setEx(connectionKey, chatVo.getRequestId(), 20, TimeUnit.SECONDS);
            return ResultUtils.ResultWithMessageEnum(HttpCodeEnum.operation_success);
        }
        //设置打断参数
        RedisUtils.setEx(connectionKey, chatVo.getRequestId(), 20, TimeUnit.SECONDS);
        return ResultUtils.ResultWithMessageEnum(HttpCodeEnum.operation_success);
    }
}
